﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace FreesenseSubAIS.Core
{
    public class BinarySerializeHelper
    {
        public static void FormatFile(string FileName, object obj)
        {
            if (!(FileName != ""))
                return;
            Stream serializationStream = (Stream)File.Open(FileName, FileMode.Create);
            new BinaryFormatter().Serialize(serializationStream, obj);
            serializationStream.Close();
        }

        public static MemoryStream FormatFile(object obj)
        {
            if (obj == null)
                return null;
            MemoryStream memoryStream = new MemoryStream();
            new BinaryFormatter().Serialize((Stream)memoryStream, obj);
            return memoryStream;
        }

        public static object DeformatFile(string FileName)
        {
            if (!File.Exists(FileName))
                return (object)null;
            if (!(FileName != ""))
                return (object)null;
            Stream serializationStream = (Stream)File.Open(FileName, FileMode.Open);
            object obj = new BinaryFormatter().Deserialize(serializationStream);
            serializationStream.Close();
            return obj;
        }

        public static object DeformatFile(MemoryStream Filestream)
        {
            if (Filestream != null)
                return new BinaryFormatter().Deserialize((Stream)Filestream);
            return (object)null;
        }
        public static bool SaveToXML(string fileName, object obj)
        {
            bool flag = true;
            try
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
                else
                    File.Create(fileName).Close();
                using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    new XmlSerializer(obj.GetType()).Serialize((Stream)fileStream, obj);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("保存xml文件error" + ex.Message);
            }
            return flag;
        }
        public static object LoadFromXML(string fileName, Type type)
        {
            try
            {
                using (StreamReader streamReader = new StreamReader(fileName))
                    return new XmlSerializer(type).Deserialize((TextReader)streamReader);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("读取xml文件error" + ex.Message);
            }
        }
    }
}
